<template>
    <n-upload name="name" directory-dnd :accept="ext" :max="1" :on-before-upload="onUploadBefore">
        <n-button size='small' v-if="!hasContent">{{ btnText }}</n-button>
        <slot name="content" v-if="hasContent"></slot>
    </n-upload>
</template>
<script setup>
/**
 * @description 上传文件组件 需要父组件传入 update 回调，当上传成功时，会触发 update 回调 回调参数为上传成功接口响应信息， 父组件处理
 * @prop {Array} ext 支持的文件类型
 * @prop {Number} size 文件大小限制
 * @prop {String} btnText 按钮文字
 * @var {Boolean} hasContent 是否有插槽 为了后续添加自定义内容
 * @author fhl 
 * @date 2024.10.31
 * @example <Upload :ext="['pdf', 'docx', 'doc']" :size="10" btnText="Upload Files" @update="onUploadSuccess"></Upload>
 */

import { useSlots } from 'vue';
import { NButton, NUpload, useMessage } from "naive-ui"

const emits = defineEmits(['update'])

const props = defineProps({
    ext: {
        type: String,
        default: '.xls,.xlsx'
    },
    size: {
        type: Number,
        default: 10
    },
    btnText: {
        type: String,
        default: 'Upload Files'
    }
})

const message = useMessage()
const slots = useSlots();
const hasContent = !!slots.content;

const onUploadBefore = async (fileObject) => {
    const file = fileObject.file.file
    const fileName = file.name.split('.');
    const fileExt = fileName.at(-1) ?? '';
    const isTypeOk = props.ext.includes(fileExt);
    const isSizeOk = file.size / 1024 / 1024 < props.size;

    if (!isTypeOk) return message.error(`只支持上传文件 ${props.ext.join(' / ')} 格式`);
    if (!isSizeOk) return message.error(`上传的文件大小不能超过 ${props.size} MB`);

    if (isTypeOk && isSizeOk) {
        onFileUpload(file)
    }
}

const onFileUpload = (file) => {
    emits('update', file)
}
</script>
<style lang='less'></style>